package com.hongguowei.lambda;

import com.hongguowei.entity.Author;
import com.hongguowei.entity.Book;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamTest {

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        System.out.println(authors);
        authors.stream()
                .distinct()
                .filter(author -> author.getId() < 10)
                .forEach(author -> System.out.println(author.getName()));
            Integer result = typeConver((String s) -> {
                return Integer.valueOf(s);
        });
        System.out.println(result);

    }

    private static void test05() {
        //获取一个map集合，key为作者名，val为List<Book>
        List<Author> authors = getAuthors();
        Map<String, List<Book>> listMap = authors.stream()
                .collect(Collectors.toMap(Author::getName, Author::getBooks));
        System.out.println(listMap);
    }

    private static void test04() {
        //获取一个所有书名的集合
        List<Author> authorList =getAuthors();
        Set<Book> bookSet = authorList.stream()
                .flatMap(author -> author.getBooks().stream())
                .collect(Collectors.toSet());
        System.out.println(bookSet);
    }

    private static void test03() {
        //存放一个所有作者名字的list集合
        List<Author> authorList = getAuthors();
        List<String> nameList = authorList.stream()
                .map(Author::getName)
                .collect(Collectors.toList());
        System.out.println(nameList);

    }
    public static <R> R typeConver (Function<String,R> function){
        String str="123";
        R result = function.apply(str);
        return result;
    }

    private static List<Author> getAuthors() {
        Author author = new Author(1, "张三", 12,null);
        Author author1 = new Author(12, "王五", 15,null);
        Author author2 = new Author(5, "孙悟空", 25,null);
        List<Book> book1 = new ArrayList<>();
        List<Book> book2 = new ArrayList<>();
        List<Book> book3 = new ArrayList<>();
        book1.add(new Book(1L,"活着",88));
        book2.add(new Book(2L,"死了",89));
        book3.add(new Book(3L,"看着",80));
        book3.add(new Book(4L,"看我",81));
        author.setBooks(book1);
        author1.setBooks(book2);
        author2.setBooks(book3);
        return new ArrayList<>(Arrays.asList(author, author1, author2));
    }
   //打印输出数组内容
    private static void test02() {
        Integer[] arr = {1, 2, 3, 4, 5};
        Stream<Integer> stream = Arrays.stream(arr);
        stream.distinct().forEach(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) {
                System.out.println(integer);
            }
        });

    }

}
